<template>
  <div style="display: flex;height: 100%">
    <!-- 关系图 -->
    <div style="width: 70%;border: 1px solid #ece6e6;">
      <div ref="chart" style="width: 100%;height:100%;"></div>
    </div>
    <!-- 列表 -->
    <div style="flex: 1;height: 100%;overflow-x: scroll">
      <el-card style="min-height: 250px;" v-for="(item, index) in analyzeData" :key="index">
        <div slot="header"><b>{{index}}列表</b></div>
        <el-table :data="analyzeData[index]" style="width: 100%;min-height: 250px;">
          <el-table-column prop="targetName" label="昵称"></el-table-column>
          <el-table-column prop="targetid" label="账户ID"></el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { detailsRelationship3 } from "@/api/combatUser/importantUser";

export default {
  name: 'relationship',
  props: {
    ID: {
      type: String,
      default: ''
    },
    userInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      analyzeData: {},
      chartInstance: null
    }
  },
  mounted() {
    detailsRelationship3(this.ID).then(res => {
      if (res.code == 200) {
        this.handleData(res.rows);
        this.$nextTick(() => {
          this.initEcharts();
        });
      } else {
        this.$message.error('获取用户数据失败！');
      }
    });
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  },
  methods: {
    handleData(data) {
      this.analyzeData = data.reduce((result, item) => {
        if (!result[item.relation]) {
          result[item.relation] = [];
        }
        result[item.relation].push(item);
        return result;
      }, {});
    console.log('this.analyzeDatathis.analyzeData', this.analyzeData);
    },

    generateChartData() {
      console.log('this.userInfothis.userInfo', this.userInfo);
      const nodes = [{
        id: this.userInfo.userId,
        name: this.userInfo.userName,
        symbolSize: 30,
        avatar: this.userInfo.avatar,
        category: '中心用户',
        itemStyle: { 
          color: '#ff6a6a',
          borderColor: '#ff6a6a',
          borderWidth: 2,
          shadowBlur: 10,
          shadowColor: '#ff6a6a'
        },
        symbol: `image://${this.userInfo.avatar}`,
        symbolSize: [50, 50],
        symbolKeepAspect: true,
        symbolClip: true
      }];

      const links = [];
      const addedIds = new Set([this.userInfo.userid]);

      console.log('ss',Object.entries(this.analyzeData));
      Object.entries(this.analyzeData).forEach(([relation, items]) => {
        items.forEach(item => {
          if (!addedIds.has(item.userid)) {
            nodes.push({
              id: item.targetid,
              avatar: item.avatar,
              name: item.targetName,
              symbolSize: 20,
              category: relation,
              itemStyle: { 
                color: relation === '关注' ? '#6aabff' : '#6aff8b',
                borderColor: relation === '关注' ? '#6aabff' : '#6aff8b',
                borderWidth: 2,
                shadowBlur: 10,
                shadowColor: relation === '关注' ? '#6aabff' : '#6aff8b'
              },
              symbol: `image://${item.avatar}`,
              symbolSize: [40, 40],
              symbolKeepAspect: true,
              symbolClip: true
            });
            addedIds.add(item.targetid);
          }

          links.push({
            source: relation === '关注' ? item.userid: item.targetid,
            target: relation === '关注' ? item.targetid : item.userid,
            lineStyle: {
              color: relation === '关注' ? '#6aabff' : '#6aff8b',
              curveness: 0.2
            },
            label: {
              show: true,
              formatter: relation,
              fontSize: 12,
              color: relation === '关注' ? '#6aabff' : '#6aff8b'
            }
          });
        });
      });

      console.log('nodes',nodes);
      console.log('links',links);
      return { nodes, links };
    },
    initEcharts() {
      if (!this.$refs.chart) return;
      
      this.chartInstance = echarts.init(this.$refs.chart);
      const { nodes, links } = this.generateChartData();

      const option = {
        tooltip: {},
        legend: {
          data: ['中心用户', '关注', '粉丝']
        },
        animationDuration: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [{
          type: 'graph',
          layout: 'force',
          force: {
            repulsion: 500,
            edgeLength: 100,
            layoutAnimation: true
          },
          data: nodes,
          links: links,
          categories: [
            { name: '中心用户' },
            { name: '关注' },
            { name: '粉丝' }
          ],
          roam: true,
          label: {
            show: true,
            position: 'bottom',
            formatter: '{b}',
            fontSize: 12,
            color: '#333'
          },
          lineStyle: {
            opacity: 0.8,
            width: 1.5
          },
          emphasis: {
            focus: 'adjacency',
            lineStyle: {
              width: 2.5
            }
          }
        }]
      };

      this.chartInstance.setOption(option);
      
      // 窗口变化时自适应
      window.addEventListener('resize', () => {
        this.chartInstance.resize();
      });
    }
  }
};
</script>

<style scoped>
.el-card {
  margin-bottom: 10px;
}
</style>